package com.dingreading.cloud.admin.util;

import com.dingreading.cloud.common.base.R;
import com.dingreading.cloud.common.util.DateUtil;
import com.dingreading.cloud.common.util.IpUtil;
import com.dingreading.cloud.common.util.aliyun.CdnUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
public class CdnUrlUtil {

    @Value("${aliYun.cdn.cdnDomain}")
    private String cdnDomain;
    @Value("${aliYun.cdn.privateKey}")
    private String cdnPrivateKey;

    /**
     * 文件获取cdn访问链接
     */
    public R<String> getCdnUrl(
            HttpServletRequest request, String url
    ) {
        if (StringUtils.isBlank(url))
            return R.fail("文件地址不存在");

        String referer = request.getHeader("referer");
        if (StringUtils.isBlank(referer)) {
            return R.fail("未获取到访问来源");
        }
        if (!referer.contains(CdnUtil.PROD_REFERER) && !referer.contains(CdnUtil.TEST_REFERER) && !referer.contains(CdnUtil.SCS_REFERER)) {
            return R.fail("请求跨域了");
        }
        String ip = IpUtil.getIpAddr(request);
        if (StringUtils.isBlank(ip)) {
            return R.fail("未获取到客户端ip");
        }

        // 2小时后过期
        Date expireTime = DateUtil.addHours(DateUtil.getNowDatetime(), 2);
        String expire = String.valueOf(expireTime.getTime());

        // 鉴权token
        String token = CdnUtil.getToken(url, ip, expire, cdnPrivateKey);
        String cdnUrl = cdnDomain + url + "?token=" + token;
        return R.ok(cdnUrl);
    }

}
